<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------

class KeywordCache
{
	// 用户编号
	private $user_id;

	// 关键词信息
	private $newKeywords;

	private $oldKeywords;

	// 原有缓存信息
	private $originalKeyword;

	// 缓存关键字
	private $cacheKey = NULL;

	private static $source = array(
			0 => 'pc',
			1 => 'wireless',
		);

	/**
	 * 初始化元素
	 * @param int  		$user_id  	用户编号
	 * @param array  	$keywords  	修改的关键词
	 */
	public function __construct($user_id, $newKeywords, $oldKeywords)
	{
		if(!$user_id)
			die('user is undefind');
		$this->cacheKey = "action_keywords_{$user_id}";

		$this->originalKeyword = $this->getCache();

		if($newKeywords) {
			$this->newKeywords = $newKeywords;
			$this->oldKeywords = $oldKeywords;
		}
			
	}

	public function handle()
	{
		if(!$this->newKeywords)
			die('keywords is undefind');
		
		$tmp = $this->originalKeyword;

		if(!isset($tmp['keyword_iids']['pc']))
			$tmp['keyword_iids']['pc'] = array();
		if(!isset($tmp['keyword_iids']['wireless']))
			$tmp['keyword_iids']['wireless'] = array();

		$pc = $tmp['keyword_iids']['pc'];
		$wireless = $tmp['keyword_iids']['wireless'];

		foreach ($this->newKeywords as $key_id => $keyword) {
			// 只允许改价的关键词进行缓存信息
			if($keyword['action'] != 'adjust')
				continue;
			foreach (self::$source as $s) {
				$ex = ($s == 'pc') ? 'price' : 'mobile_price';
				if($s == 'wireless' && (int)$keyword['mobile_is_default_price'] == 1)
					continue;
				if(!isset($this->oldKeywords[$key_id]['new_'. $ex]))
					continue;
				$tmp['keyword_info'][$key_id]['action'] = $keyword['action'];
				if(!in_array($key_id, $tmp['keyword_iids'][$s]))
					$tmp['keyword_iids'][$s][] = (string)$key_id;
				$tmp['keyword_info'][$key_id][$s] = price_display_str($this->oldKeywords[$key_id][$ex]/100);
			}
		}

		$tmp['all_keyword_iids'] = array_unique(array_merge($tmp['keyword_iids']['pc'], $tmp['keyword_iids']['wireless']));

		$this->saveCache($this->cacheKey, $tmp, $this->getExpire());
	}

	private function getExpire()
	{
		return strtotime(date('Y-m-d',strtotime('+1 day')))-time();
	}

	public function setParams($data)
	{
		// todo
	}

	private function getCache()
	{
		return S($this->cacheKey);
	}

	private function saveCache($key, $value, $expire)
	{
		S($key, $value, $expire);
	}
}